package com.itheima.pxgl.cotroller;

import com.itheima.pxgl.common.Result;
import com.itheima.pxgl.common.constant.JwtClaimsConstant;
import com.itheima.pxgl.common.properties.JwtProperties;
import com.itheima.pxgl.entity.pojo.ApUser;
import com.itheima.pxgl.service.loginService;
import com.itheima.pxgl.utils.JwtUtil;
import com.itheima.pxgl.entity.vo.LoginVo;
import com.itheima.pxgl.entity.vo.userVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping
@RestController
public class loginController {
    @Autowired
    private loginService loginService;
    @Autowired
    private JwtProperties jwtProperties;

    /**
     * 用户登录
     * @param userVo
     * @return
     */
    @PostMapping("/login")
    public Result<LoginVo> login(@RequestBody userVo userVo){
        log.info("用户登录{}",userVo);
        ApUser apUser = loginService.login(userVo);
//        登录成功后，返回token
        Map<String, Object> claims = new HashMap<>();
        claims.put(JwtClaimsConstant.EMP_ID, apUser.getUserId());
        String token = JwtUtil.createJWT(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
//        log.info("用户登录成功，产生token{}",token);
        LoginVo loginVo = LoginVo.builder()
                .token(token)
                .userName(apUser.getUsername())
                .id(Long.valueOf(apUser.getUserId()))
                .build();
        return Result.success(loginVo);
    }

    /**
     * 注册
     * @param userVo
     * @return
     */
    @PostMapping("/reg")
    public Result register(@RequestBody userVo userVo ) {
        log.info("用户注册，{}", userVo);
        loginService.register(userVo);
        return Result.success();
    }
}
